package cn.johnyu;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

public class SimpleLuceneExample {

    public static void main(String[] args) throws Exception {
        // 创建一个内存索引库
        Directory memoryIndex = new RAMDirectory();

        // 使用标准分析器
        StandardAnalyzer analyzer = new StandardAnalyzer();

        // 配置 IndexWriter
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);

        // 创建 IndexWriter
        try (IndexWriter writer = new IndexWriter(memoryIndex, indexWriterConfig)) {
            addDocument(writer, "Hello Lucene",5);
            addDocument(writer, "你好 Lucene",6);
            addDocument(writer, "john Lucene",2);
            addDocument(writer, "john hello",3);
        }

        // 搜索文本 "Lucene"ND
        searchInIndex(memoryIndex, analyzer, "john NOT Lucene");

    }

    private static void addDocument(IndexWriter writer, String content,int id) throws Exception {
        // 创建文档并添加字段
        Document document = new Document();
        document.add(new TextField("content", content, Field.Store.NO));

        document.add(new TextField("id", id+"", Field.Store.YES));

        // 将文档写入索引
        writer.addDocument(document);

    }

    private static void searchInIndex(Directory index, StandardAnalyzer analyzer, String queryString) throws Exception {
        // 创建查询解析器
        QueryParser parser = new QueryParser("content", analyzer);

        // 解析查询
        Query query = parser.parse(queryString);

        // 读取索引
        try (IndexReader reader = DirectoryReader.open(index)) {
            IndexSearcher searcher = new IndexSearcher(reader);

            // 执行搜索
            TopDocs topDocs = searcher.search(query, 10);

            // 显示搜索结果
            System.out.println("Found " + topDocs.totalHits + " hits.");
            for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
                Document doc = searcher.doc(scoreDoc.doc);
                System.out.println("Doc ID: " + scoreDoc.doc + " - Content: " + doc.get("content"));
                System.out.println("Doc ID: " + scoreDoc.doc + " - Content: " + doc.get("id"));
            }
        }
    }
}
